$(function(){
	$(".split-tr-instance").each(function() {
		editSplit($(this).find(".splitBox").get(0));
	});
});

// 全选、取消全选的事件
function selectAll() {
	if ($("#box_all").prop("checked")) {
		$(".id_box").prop("checked", true);
	} else {
		$(".id_box").prop("checked", false);
	}
}
// 子复选框的事件
function setSelectAll(){
	//当没有选中某个子复选框时，SelectAll取消选中
	var chsub = $(".id_box").length; //获取subcheck的个数
	var checkedsub = $(".id_box:checked").length; //获取选中的subcheck的个数
	if (checkedsub == chsub) {
		$("#box_all").prop("checked", true);
	} else {
		$("#box_all").prop("checked", false);
	}
}

// 对应大白话的勾选事件
function mappingSlangFlag(obj) {
	var param = {id:$(obj).val()};
	if($(obj).prop("checked")) {
		param.slang = "";
	}
	API.elementMappingSlang(param, function(res) {
		if(res.code == 0) {
			
		} else {
			alert(res.desc);
		}
	});
}

function elementExport(obj, property) {
    if(!property) {
        alert("请选择一种属性！");
        return false;
    }
	if(UTIL.checkButton(obj)) {
		window.location.href="/vocab/element_export.htm?property=" + property;
		UTIL.releaseButton(obj);
	}
}

function splitWord(obj,id) {
	if($(obj).parents("tr").next().is(":hidden")) {
        $( "tr[name=split_word_"+id+"]" ).each( function() {
            $( this ).show();
        } );
	} else { // 如果是打开了分割列，则再点击按钮就把分割列关闭
        $( "tr[name=split_word_"+id+"]" ).each( function() {
            $( this ).hide();
        } );
	}
}

function editSplit(obj) {
	var _obj = $(obj);
	var splitTr = _obj.parents("tr");
	var initProp = splitTr.find(".initProp").val();
	
	// 如果是编辑词语，则校验是否需要增删拆词个数
	if(_obj.attr("class") == 'splitWord') {
		if($.trim(_obj.val())) {
			// 有内容则判断是否需要添加
			if(_obj.parents(".split-div-word").next().attr("class") == 'split-div-submit') {
				var wordDiv = $(".split-tr").find(".split-div-word").clone();
				wordDiv.find("select").val(initProp);
				_obj.parents(".split-div-word").after(wordDiv);
				_obj.parents(".split-div-word").after($(".split-tr").find(".split-div-plus").clone());
			}
		} else {
			// 如果超过两个词语且当前词语不是最后一个词语则删除
			if(_obj.parents(".split-tr-instance").find(".split-div-word").size() > 2 && _obj.parents(".split-div-word").next().attr("class") == 'split-div-plus') {
				_obj.parents(".split-div-word").next().remove();
				_obj.parents(".split-div-word").remove();
			}
		}
	}
	
	// 维护拆词后结果
	var splitWords = splitTr.find(".splitWord");
	if(splitWords.length > 2) {
		// 如果拆分词语有两个或以上则表示需要拆分
		var splitProperties = splitTr.find(".splitProperty");
		var splitBoxs = splitTr.find(".splitBox");
		var splitValue = "";
		var splitDisplay = "";
		for(var i=0; i<splitWords.length; i++) {
			if($(splitWords.get(i)).val()) {
				var box = $(splitBoxs.get(i)).prop("checked");
				var boxValue = "0";
				if(box) {
					boxValue = "1";
				}
				
				splitValue += boxValue + " " + $.trim($(splitWords.get(i)).val()) + " " + $(splitProperties.get(i)).val() + ",";
				splitDisplay += $.trim($(splitWords.get(i)).val()) + " " + $(splitProperties.get(i)).val() + ",";
			}
		}
		splitTr.find("[name='splitValue']").val(splitValue);
		splitTr.prev().find(".splitDisplay").html(splitDisplay);
		var id = splitTr.find("input[name=splitValue]").attr("id");
		var split = "";
        $("[dataid=split_word_"+id+"]").each(function (){
            split += $(this).val();
            split +="\n";
        });
        $("div[dataid=splitDisplay_"+id+"]").attr("title",split);
		// 替换功能关闭
		splitTr.prev().find(".replace").hide();
	} else {
		// 拆分词语不足两个表示不拆分
		splitTr.find("[name='splitValue']").val("");
		splitTr.prev().find(".splitDisplay").html("");
		
		// 替换功能打开
		splitTr.prev().find(".replace").show();
	}
}

function submitPage(obj) {
	if(UTIL.checkButton(obj)) {
		// 将正误判断设置到隐藏框中
		$(".id_box").each(function () {
			if($(this).prop("checked")) {
				$(this).next().val("0");
			} else {
				$(this).next().val("1");
			}
		});
		
		if(checkSplit()) {
			// 由于拆分词语有多个所以不能直接serialize
            var ids = "";
			$("[name='dataId']").each(function (){
				ids = ids + $(this).val();
				ids += ",";
            });
			var idArr = ids.substring(0,ids.length-1).split(",");
			var flags = "";
            $("[name='flag']").each(function (){
                flags = flags + $(this).val();
                flags += ",";
            });
            var replaceVocabs = "";
            $("[name='replaceVocab']").each(function (){
                replaceVocabs = replaceVocabs + $(this).val();
                replaceVocabs += ",";
            });
            var replaceProp = "";
            $("[name='replaceProp']").each(function (){
                replaceProp = replaceProp + $(this).val();
                replaceProp += ",";
            });
            var splitWordAll="";
			for(var i=0;i<idArr.length;i++){
				var splitWord = "";

                $("[dataid=split_word_"+idArr[i]+"]").each(function (){
                	if($(this).val()){

                        splitWord = splitWord + $(this).val();
                        splitWord += "|";
                    }
                });
                splitWordAll += splitWord;
                splitWordAll += "@";
            }

			var formData = { "ids":ids,"flag":flags,"replaceVocabs":replaceVocabs,"replaceProp":replaceProp,"splitWord":splitWordAll};
			API.elementCheckPage(formData, function(res) {
				UTIL.releaseButton(obj);
				if (res.code == '0') {
					window.location.reload();
					UTIL.releaseButton(obj);
					return true;
				} else {
					alert(res.desc);
				}
			});
		} else {
			UTIL.releaseButton(obj);
		}
		
		return true;
	}
}

// 校验分拆参数
function checkSplit() {
	var flagErrMsg = "";
	// 校验替换属性和词语不能是本身，有替换则必是错误词语
	var replaceVocabErrMsg = "";
	$("[name='replaceVocab']").each(function (){
		var replaceVocabVal = $.trim($(this).val());
		if(replaceVocabVal) {
			var vocabVal = $(this).prev().html();
			var propVal = $(this).parent().next().find("span").html();
			if(replaceVocabVal == vocabVal) {
				if(!replaceVocabErrMsg) {
					replaceVocabErrMsg = "替换词语不能是其本身：";
				}
				replaceVocabErrMsg += vocabVal + ",";
			}
			
			if($(this).parents("tr").find("[name='flag']").val() == '0') {
				$(this).parents("tr").find("[name='flag']").val(1);
			}
		}
	});
	replaceVocabErrMsg && (replaceVocabErrMsg += "\n");

	var replacePropErrMsg = "";
	$("[name='replaceProp']").each(function (){
		var replaceProp = $(this).val();
		if($.trim(replaceProp)) {
			var propVal = $(this).prev().html();
			var vocabVal = $(this).parent().prev().find("span").html();
			if(replaceProp == propVal) {
				if(!replacePropErrMsg) {
					replacePropErrMsg = "替换属性不能是其本身：";
				}
				replacePropErrMsg += "(" + vocabVal + " " + propVal + "),";
			}
			
			if($(this).parents("tr").find("[name='flag']").val() == '0') {
				$(this).parents("tr").find("[name='flag']").val(1);
			}
		}
	});
	replacePropErrMsg && (replacePropErrMsg += "\n");

	var replacePropEmptyErrMsg = "";
	$(".splitWord").each(function (){
		var splitWord = $(this).val();
		var splitProp = $(this).next().val();
		if(splitWord && !splitProp) {
			var propVal = $(this).parents("tr").prev().find(".property").html();
			var vocabVal = $(this).parents("tr").prev().find(".vocabulary").html();
			if(!replacePropEmptyErrMsg) {
				replacePropEmptyErrMsg = "请给拆分后的词选择属性：";
			}
			replacePropEmptyErrMsg += "(" + vocabVal + " " + propVal + "),";
		}
	});
	replacePropEmptyErrMsg && (replacePropEmptyErrMsg += "\n");
	
	// 校验拆词属性是否正确，有拆分必是错误词语
	var splitPropErrMsg = "", splitNodeErrMsg = "";
	$("[name='splitValue']").each(function (){
		var splitValue = $.trim($(this).val());
		if(splitValue) {
			var propVal = $(this).parents("tr").find(".initProp").val();
			var vocabVal = $(this).parents("tr").find(".initVocabulary").val();
			var nodeCount = 0; // 判断并列的词语个数
			var temp1 = splitValue.split(",");
			for(var i=0;i<temp1.length;i++) {
				var temp2 = temp1[i].split(" ");
				if(temp2[0] == 1) {
					nodeCount ++;
				}
			}
			
			if(nodeCount == 1) {
				if(!splitNodeErrMsg) {
					splitNodeErrMsg = "拆词的并列词语至少有两个：";
				}
				splitNodeErrMsg += "(" + vocabVal + " " + propVal + "),";
			}

			if($(this).parents("tr").prev().find("[name='flag']").val() == '0') {
				$(this).parents("tr").prev().find("[name='flag']").val(1);
			}
		}
	});
	splitNodeErrMsg && (splitNodeErrMsg += "\n");
	flagErrMsg && (flagErrMsg += "\n");
	
	var errMsg = flagErrMsg + replaceVocabErrMsg + replacePropErrMsg + splitPropErrMsg + splitNodeErrMsg + replacePropEmptyErrMsg;
	if(errMsg) {
		alert(errMsg);
		return false;
	}
	
	return true;
}

function changeReplaceProp(obj) {
	var replaceProp = $(obj).val();
	var property = $(obj).prev().html();
	if(replaceProp && replaceProp!=' ') {
		$(obj).parents("tr").next().find(".initProp").val(replaceProp);
		$(obj).parents("tr").next().find("select").val(replaceProp);
	} else {
		$(obj).parents("tr").next().find(".initProp").val(property);
		$(obj).parents("tr").next().find("select").val(property);
	}
}

// 删除分拆
function deleteSplit(obj, eid) {
	var vocabulary = $(obj).parents("tr").find(".vocabulary").html();
	var property = $(obj).parents("tr").next().find(".initProp").val();
	
	var splitDivs = $(obj).parents("tr").next().find(".split-div-word");
	var splitPluses = $(obj).parents("tr").next().find(".split-div-plus");
	
	for(var i=0;i<splitDivs.length - 1;i++) {
		if(i == 0) {
			$(splitDivs[i]).find(".splitWord").val(vocabulary);
			$(splitDivs[i]).find(".splitProperty").val(property);
			$(splitDivs[i]).find(".splitBox").prop("checked", false);
		} else {
			$(splitDivs[i]).remove();
			$(splitPluses[i]).remove();
		}
	}
	var k = 1;
	// 删除多余的tr
    $("tr[name='split_word_"+eid+"']").each(function(){


    	if(k!=1){
    		$(this).remove();
		}

		k++;
    });
    // 替换功能打开
	$(obj).parents("tr").find(".replace").show();
	
	$(obj).parents("tr").next().find("[name='splitValue']").val("");
	
	$(obj).remove();
}

// 更改量化
function changeQuantization(obj, id) {
	var quantization = $(obj).val();
	API.elementChangeTimeQuantization({"id": id, "quantization": quantization}, function(res) {
		if (res.code == '0') {
		} else {
			alert(res.desc);
		}
	});
}

function changeCountPerPage(obj) {
	var countPerPage = $(obj).val();
    var g = /^[1-9]*[1-9][0-9]*$/;
	if(g.test(countPerPage)) {
		window.location.href = "element_list.htm?countPerPage=" + countPerPage;
	}
}


function upload(url, name, obj) {
	var ids = "";
	$("input[name='synonymyAdd']:checked").each(function(){ 
		ids+=$(this).val()+","; 
		//alert($(this).val()); 
	}); 
	if(!ids){
		alert("请选择添加的同义词")
		return;
	}
	var param = {
			"id" : ids,
			"name" : name
	};
	API.elementRAddSynonymy( param, function(res) {
		if (res.code == '0') {
			$(obj).dialog("close");
			alert("添加成功");
		} else {
			alert(res.desc);
		}
	});
}

function checkedAll(obj){
    if($(obj).prop("checked")){ 
        $("input[name='synonymyAdd']").prop("checked", true);
    }else{ 
        $("input[name='synonymyAdd']").prop("checked", false);
    }
}

//分词标注问题标志
function checkAnalysisFlag(obj) {

	var analysisFlag = "0";
	if($(obj).prop("checked")) {
		analysisFlag = "1";
	}
	var id = $(obj).val();
	var param = { "analysisFlag" : analysisFlag, "id" : id }
	API.elementAnalysisFlagCheck(param, function(res) {
		if(res.code == 0) {
			
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

function addSplit(obj,id,vocab,prop){
    $("#copy_split").attr("name","split_word_"+id);
    $( "tr[name=split_word_"+id+"]:last").after($("#copy_split").clone());
    $( "tr[name=split_word_"+id+"]:last").show();
    $( "tr[name=split_word_"+id+"]:last").find("[name='splitValue']").attr("dataid","split_word_"+id);
    $( "tr[name=split_word_"+id+"]:last").find("[name='splitValue']").attr("id",id);
    $( "tr[name=split_word_"+id+"]:last").find("[class='initVocabulary']").val(vocab);
    $( "tr[name=split_word_"+id+"]:last").find("[class='initProp']").val(prop);

}
